#pragma once
#include <iostream>
#include <string>
#include "../comm/httplib.h"
#include <jsoncpp/json/json.h>
#include "cookie.hpp"
#include "../comm/util.hpp"
#include "../comm/log.hpp"

using namespace std;
using namespace httplib;
using namespace ns_util;
using namespace ns_log;

void handle_compile(const Request &req, Response &res)
{
    // 检查 Cookie
    if (!check_cookie(req))
    {
        res.status = 401; // 未授权
        res.set_content("未授权，请登录", "text/plain;charset=utf-8");
        return;
    }

    // 从请求中获取请求体
    std::string in_json = req.body;

    // 检查请求体是否为空
    if (in_json.empty())
    {
        res.status = 400; // 请求错误
        res.set_content("请求体为空", "text/plain;charset=utf-8");
        LOG(ERROR) << "Received empty JSON request body." << std::endl;
        return;
    }

    // 解析 JSON 数据
    Json::Value in_value;
    Json::Reader reader;
    bool parsingSuccessful = reader.parse(in_json, in_value);

    // 检查是否成功解析 JSON
    if (!parsingSuccessful)
    {
        // JSON 解析失败，输出错误信息并返回
        LOG(ERROR)<< "Failed to parse JSON: " << reader.getFormattedErrorMessages() << std::endl;
        return;
    }

    // 提取代码字段
    std::string code = in_value["code"].asString();

    // 检查 code 是否为空
    if (code.empty())
    {
        res.status = 400; // 请求错误
        res.set_content("代码不能为空", "text/plain;charset=utf-8");
        LOG(ERROR)<< "Received empty code from request." << std::endl;
        return;
    }

    Json::Value compile_value;
    compile_value["code"] = code;
    compile_value["cpu_limit"] = 1;
    compile_value["mem_limit"] = 1024 * 1024 * 10;

    Json::FastWriter writer;
    string compile_string = writer.write(compile_value);

    // 模拟调用远程服务（这里假设使用了 Client 类来发送请求）
    std::string out_json;
    Client client("127.0.0.1", 8888);
    auto resp = client.Post("/compile_and_run", compile_string, "application/json;charset=utf-8");

    // 检查服务端响应状态
    if (resp && resp->status == 200)
    {
        out_json = resp->body;
        // 设置响应内容
        res.status = 200;
        res.set_content(out_json, "application/json;charset=utf-8");
    }
    else
    {
        res.status = 500;
        Json::Value error_value;
        error_value["reason"] = "编译服务不可用";
        Json::FastWriter writer;
        std::string error_string = writer.write(error_value);
        res.set_content(error_string, "application/json;charset=utf-8");
    }
}